package cn.cctvcc.security.feign;

import cn.cctvcc.core.constant.SecurityConstants;
import cn.cctvcc.core.utils.ServletUtils;
import cn.cctvcc.core.utils.StringUtil;
import cn.cctvcc.core.utils.ip.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * @description: feign 请求拦截器
 * @author: Jiang
 * @create: 2021-09-23 22:01
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (!Objects.isNull(httpServletRequest)) {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            // 传递用户信息请求头，防止丢失
            String userId = headers.get(SecurityConstants.DETAILS_USER_ID);
            if (StringUtil.isNotEmpty(userId))
                requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);

            String userName = headers.get(SecurityConstants.DETAILS_USERNAME);
            if (StringUtil.isNotEmpty(userName))
                requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);

            String authentication = headers.get(SecurityConstants.AUTHORIZATION_HEADER);
            if (StringUtil.isNotEmpty(authentication))
                requestTemplate.header(SecurityConstants.AUTHORIZATION_HEADER, authentication);

            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));
        }
    }
}